#!/bin/bash

CURRENT_USER=$(echo $USER)
if [ "$CURRENT_USER" != 'root' ]; then
    echo "Permission denied by user $CURRENT_USER. Add 'sudo' before the command."
    exit -1
fi

ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
mkdir /root/.pip
echo "[global]
index-url = https://mirrors.aliyun.com/pypi/simple/

[install]
trusted-host=mirrors.aliyun.com
" > /root/.pip/pip.conf

rm -f /etc/apt/sources.list.bak
mv /etc/apt/sources.list /etc/apt/sources.list.bak
touch /etc/apt/sources.list
echo "deb http://mirrors.aliyun.com/raspbian/raspbian/ stretch  main non-free contrib
deb-src http://mirrors.aliyun.com/raspbian/raspbian/ stretch main non-free contrib" > /etc/apt/sources.list

mv /etc/apt/sources.list.d/raspi.list /etc/apt/sources.list.d/raspi.list.bak

if [[ ! -f /usr/bin/git ]] || [[ ! -f /usr/bin/ffmpeg ]] || [[ ! -f /usr/local/bin/pip3 ]];then
    while true;do
        apt-get update
        apt-get install ffmpeg python3-pip expect git -y
        if [[ $? == 0 ]];then
            break
        fi
    done
fi

if [[ -d /var/device/kafka-rest-client-py ]]; then
    echo "device is already inited."
    exit 0
fi

pip3 install -i https://mirrors.aliyun.com/pypi/simple pycryptodome pika
sed -i "13a service ssh start" /etc/rc.local

mkdir /var/device
mkdir /etc/pki
cd /var/device
git clone https://gitee.com/hongen-ek/kafka-rest-client-py.git
cd kafka-rest-client-py
git config core.filemode false
chmod 755 /var/device/kafka-rest-client-py/python_daemon.sh
mkdir -p /usr/lib/systemd/system
cat << EOF > /usr/lib/systemd/system/pythondaemon.service
[Unit]

Description=python_daemon

[Service]

Type=simple

ExecStart=/var/device/kafka-rest-client-py/python_daemon.sh

[Install]

WantedBy=multi-user.target
EOF

systemctl enable pythondaemon.service
systemctl start pythondaemon.service

#echo 0 | tee /sys/class/leds/led0/brightness
# sudo sed -i "14d" /etc/rc.local
# sudo sed -i "19d" /etc/rc.local

sed -i "15a 0  0    * * *   root    /bin/bash /var/device/kafka-rest-client-py/handle.sh" /etc/crontab